package com.lsyw.intergrate.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.common.StringUtil;
import com.lsyw.intergrate.common.util.DateUtil;
import com.lsyw.intergrate.entity.*;
import com.lsyw.intergrate.entity.common.LoginInfo;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.lsyw.intergrate.entity.qo.LoginQo;
import com.lsyw.intergrate.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.lsyw.intergrate.common.MybatisPlus.ColumnResolver.massifUserCR;
import static com.lsyw.intergrate.common.Result.errorResult;
import static com.lsyw.intergrate.common.Result.successResult;
import static com.lsyw.intergrate.common.util.PositionUtil.getDistance4;

/**
 * <p>
 * 移动端前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-04-18
 */
@Api(tags = "移动端司机、过磅员、接收人接口")
@RestController
@RequestMapping("/appDriver")
public class APPDriverController {

    @Autowired
    private TransportWorkOrderService transportWorkOrderService;
    @Autowired
    private TransportTaskService transportTaskService;
    @Autowired
    private VehicleService vehicleService;

    /**
     * 通过id查询
     */
    @GetMapping("/getVehicle")
    @ApiOperation(value = "获取当前司机的车辆", httpMethod = "GET")
    public Result getVehicle() {
        return vehicleService.getVehicle();
    }

    /**
     * 新增
     */
    @PostMapping("/createWorkOrder")
    @ApiOperation(value = "司机-任务详情中创建工单", httpMethod = "POST")
    public Result createWorkOrder(@RequestBody TransportWorkOrder transportWorkOrder) {
        String loginId;
        try {
            loginId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return new Result(4414, "登录过期，请重新登录", "登录过期，请重新登录");
        }
        TransportTask transportTask =transportTaskService.getById(transportWorkOrder.getTransportTaskId());

        transportWorkOrder.setDelFlag(0);
        transportWorkOrder.setStatus(1);
        transportWorkOrder.setGmtCreateUser(loginId);
        transportWorkOrder.setDriverId(loginId);
        transportWorkOrder.setGmtCreate(new Date());
        if (Objects.nonNull(transportWorkOrder.getVehicle())) {
            if (StringUtil.isEmpty(transportWorkOrder.getVehicle().getId())) {
                transportWorkOrder.getVehicle().setDelFlag(0);
                transportWorkOrder.getVehicle().setStatus(1);
                transportWorkOrder.getVehicle().setDriverId(loginId);
                transportWorkOrder.getVehicle().setGmtCreateUser(loginId);
                transportWorkOrder.getVehicle().setGmtCreate(new Date());
                vehicleService.save(transportWorkOrder.getVehicle());
            } else {
                vehicleService.updateById(transportWorkOrder.getVehicle());
            }
            transportWorkOrder.setVehicleId(transportWorkOrder.getVehicle().getId());
        } else {
            return Result.errorResult("请绑定车辆");
        }
        transportWorkOrder.setName(transportTask.getName()+" "+ DateUtil.format(new Date(),DateUtil.DATE_PATTON_DEFAULT_HOUR)+" "+transportWorkOrder.getVehicle().getPlateNumber());
        transportWorkOrderService.save(transportWorkOrder);
        return Result.successResult(null);
    }

    /**
     * 通过id删除
     */
    @GetMapping("/delete-by-id/{id}")
    @ApiOperation(value = "司机-删除工单", httpMethod = "GET")
    public Result delete(@PathVariable(value = "id") String id) {
        String loginId;
        try {
            loginId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return new Result(4414, "登录过期，请重新登录", "登录过期，请重新登录");
        }
        TransportWorkOrder transportWorkOrder = transportWorkOrderService.getById(id);
        if (transportWorkOrder.getStatus() != 1) {

            if (!transportWorkOrder.getGmtCreateUser().equals(loginId)) {
                return Result.errorResult("只能删除未本人创建的工单");
            }
            transportWorkOrder.setDelFlag(1);
            transportWorkOrder.setGmtModified(new Date());
            transportWorkOrderService.updateById(transportWorkOrder);

        }
        return Result.successResult(null);
    }

    /**
     * 分页查询
     */
    @PostMapping("/taskPage")
    @ApiOperation(value = "司机-运输任务列表-分页", notes = "司机-运输任务列表-分页", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition:companyId", value = "运输公司/团队 ", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:massifId", value = "地块Id", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:startTime", value = "开始时间  年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:endTime", value = "结束时间 年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:transportPlanId", value = "运输计划", required = false, paramType = "query", dataType = "String")
    })
    public Result taskPage(@RequestBody PageInfo pageInfo) {
        Page<TransportTask> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        return Result.successResult(this.transportTaskService.pageAppList(page, pageInfo.getCondition()));
    }

    /**
     * 分页查询
     */
    @PostMapping("/workOrderPage")
    @ApiOperation(value = "司机-运输历史记录列表-分页", notes = "司机-运输历史记录列表-分页", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition:companyId", value = "运输公司/团队 ", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:massifId", value = "地块Id", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:name", value = "工单名称", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:startTime", value = "开始时间  年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:endTime", value = "结束时间 年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:transportPlanId", value = "运输计划", required = false, paramType = "query", dataType = "String")
    })
    public Result workOrderPage(@RequestBody PageInfo pageInfo) {
        String loginId;
        try {
            loginId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return new Result(4414, "登录过期，请重新登录", "登录过期，请重新登录");
        }
        Page<TransportWorkOrder> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        pageInfo.getCondition().put("gmtCreateUser", loginId);
        return Result.successResult(this.transportWorkOrderService.pageAppList(page, pageInfo.getCondition()));
    }

    /**
     * 分页查询
     */
    @GetMapping("/getWorkOrderDetail")
    @ApiOperation(value = "运输历史明细", notes = "运输历史明细", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workOrderId", value = "工单Id", required = false, paramType = "query", dataType = "String")
    })
    public Result getWorkOrderDetail(String workOrderId) {
        return Result.successResult(this.transportWorkOrderService.getWorkOrderDetail(workOrderId));
    }


    /**
     * 分页查询
     */
    @PostMapping("/dzc_workOrderPage")
    @ApiOperation(value = "过磅员-待装车列表-分页", notes = "过磅员-待装车列表-分页", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition:companyId", value = "运输公司/团队 ", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:massifId", value = "地块Id", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:name", value = "工单名称", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:startTime", value = "开始时间  年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:endTime", value = "结束时间 年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:transportPlanId", value = "运输计划", required = false, paramType = "query", dataType = "String")
    })
    public Result dzc_workOrderPage(@RequestBody PageInfo pageInfo) {
        Page<TransportWorkOrder> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        pageInfo.getCondition().put("status", 1);
        return Result.successResult(this.transportWorkOrderService.pageAppList(page, pageInfo.getCondition()));
    }

    /**
     * 分页查询
     */
    @PostMapping("/gbls_workOrderPage")
    @ApiOperation(value = "过磅员-过磅历史列表-分页", notes = "过磅员-过磅历史列表-分页", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition:companyId", value = "运输公司/团队 ", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:massifId", value = "地块Id", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:name", value = "工单名称", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:startTime", value = "开始时间  年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:endTime", value = "结束时间 年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:transportPlanId", value = "运输计划", required = false, paramType = "query", dataType = "String")
    })
    public Result gbls_workOrderPage(@RequestBody PageInfo pageInfo) {
        String loginId;
        try {
            loginId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return new Result(4414, "登录过期，请重新登录", "登录过期，请重新登录");
        }
        Page<TransportWorkOrder> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        pageInfo.getCondition().put("weigherId", loginId);
        return Result.successResult(this.transportWorkOrderService.pageAppList(page, pageInfo.getCondition()));
    }

    /**
     * 新增
     */
    @PostMapping("/saveWeigher")
    @ApiOperation(value = "过磅员-信息录入", notes = "过磅员-信息录入", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "weight", value = "土量", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "cctvIds", value = "cctvid ", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "weighterId", value = "过磅员id", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "volume", value = "体积", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "gpsSoilId", value = "GPS--土壤中id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "gpsVehicleId", value = "GPS--车辆中id", required = true, paramType = "query", dataType = "String")
    })
    public Result saveWeigher(@RequestBody Map<String, Object> map) {
        TransportWorkOrder transportWorkOrder = transportWorkOrderService.getById(map.get("id").toString());
        if (Objects.nonNull(map.get("weight"))) {
            transportWorkOrder.setWeight(Double.parseDouble(map.get("weight").toString()));
        }
        if (Objects.nonNull(map.get("volume"))) {
            transportWorkOrder.setVolume(Double.parseDouble(map.get("volume").toString()));
        }
        if (Objects.nonNull(map.get("gpsSoilId"))) {
            transportWorkOrder.setGpsSoilId(map.get("gpsSoilId").toString());
        }
        if (Objects.nonNull(map.get("gpsVehicleId"))) {
            transportWorkOrder.setGpsVehicleId(map.get("gpsVehicleId").toString());
        }
        transportWorkOrder.setStatus(2);
        transportWorkOrder.setCctvIds(map.get("cctvIds").toString());
        transportWorkOrder.setWeigherId(map.get("weighterId").toString());
        transportWorkOrder.setGmtModified(new Date());
        transportWorkOrderService.updateById(transportWorkOrder);
        return Result.successResult(null);
    }


    /**
     * 分页查询
     */
    @PostMapping("/jsls_workOrderPage")
    @ApiOperation(value = "接收员-接收历史列表-分页", notes = "接收员-接收历史列表-分页", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition:companyId", value = "运输公司/团队 ", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:massifId", value = "地块Id", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:name", value = "工单名称", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:startTime", value = "开始时间  年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:endTime", value = "结束时间 年-月-日", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "condition:transportPlanId", value = "运输计划", required = false, paramType = "query", dataType = "String")
    })
    public Result jsls_workOrderPage(@RequestBody PageInfo pageInfo) {
        String loginId;
        try {
            loginId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return new Result(4414, "登录过期，请重新登录", "登录过期，请重新登录");
        }
        Page<TransportWorkOrder> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        pageInfo.getCondition().put("receiveId", loginId);
        return Result.successResult(this.transportWorkOrderService.pageAppList(page, pageInfo.getCondition()));
    }


    /**
     * 新增
     */
    @PostMapping("/saveReceive")
    @ApiOperation(value = "接收员-信息录入", notes = "接收员-信息录入", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "工单id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isIn", value = "是否入库", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "sjWay", value = "利用处置方式", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "receiveWeight", value = "土量-接收员", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "receiveVolume", value = "体积-接收员", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "receiveUnit", value = "接收单位", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "receivePerson", value = "接收人", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "receivePhone", value = "接收人电话", required = true, paramType = "query", dataType = "String")
    })
    public Result saveReceive(@RequestBody Map<String, Object> map) {
        String loginId;
        try {
            loginId = StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return new Result(4414, "登录过期，请重新登录", "登录过期，请重新登录");
        }
        TransportWorkOrder transportWorkOrder = transportWorkOrderService.getById(map.get("id").toString());
        transportWorkOrder.setReceiveWeight(Double.parseDouble(map.get("receiveWeight").toString()));
        if (Objects.nonNull(map.get("receiveVolume"))) {
            transportWorkOrder.setReceiveVolume(Double.parseDouble(map.get("receiveVolume").toString()));
        }

        if (Objects.nonNull(map.get("receiveUnit"))) {
            transportWorkOrder.setReceiveUnit(map.get("receiveUnit").toString());
        }
        if (Objects.nonNull(map.get("receivePerson"))) {
            transportWorkOrder.setReceivePerson(map.get("receivePerson").toString());
        }
        if (Objects.nonNull(map.get("receivePhone"))) {
            transportWorkOrder.setReceivePhone(map.get("receivePhone").toString());
        }
        if (Objects.nonNull(map.get("isIn"))) {
            transportWorkOrder.setIsIn(Integer.parseInt(map.get("isIn").toString()));
        }
        if (Objects.nonNull(map.get("sjWay"))) {
            transportWorkOrder.setSjWay(Integer.parseInt(map.get("sjWay").toString()));
        }

        transportWorkOrder.setStatus(3);
        transportWorkOrder.setReceiveId(loginId);
        transportWorkOrder.setReceiveDate(new Date());
        transportWorkOrder.setGmtModified(new Date());
        transportWorkOrderService.updateById(transportWorkOrder);
        return Result.successResult(null);
    }
}
